package com.storyroad.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONException;
import org.json.JSONObject;

import com.storyroad.responseClasses.FollowObject;
import com.storyroad.utils.DBConnection;
import com.storyroad.utils.TableNames;
import com.storyroad.utils.Utilities;

/**
 * Servlet implementation class GetFollowers
 */
public class GetFollowers extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public GetFollowers() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * Finds the followers of a user. A list of {@link com.storyroad.responseClasses.FollowObject} instances which contain
	 * information about the followers is returned to the front-end.
	 * @param request HttpServletRequest object that contains data coming from front-end
	 * @param response HttpServletResponse object that contains data which is prepared after processing the incoming data
	 * @throws IOException
	 * @throws ServletException
	 */
	protected void process(HttpServletRequest request,
			HttpServletResponse response) throws IOException, ServletException {

		// List of FollowObject instances that will be returned to the front-end.
		ArrayList<FollowObject> followedPeople = new ArrayList<FollowObject>();
		String f_requestType = request.getParameter("request_type");
		String f_username;
		if (f_requestType == null || !f_requestType.equals("Android")) {
			f_requestType = "Web";
			f_username = (String) request.getSession().getAttribute("username");
			if (f_username == null) {
				// Check whether this action is performed by a registered user. If not, the user is redirected to the login page.
				response.sendRedirect(response.encodeRedirectURL(request.getContextPath() + "/LoginPage.jsp"));
				return;
			}
		} else {
			f_username = (String) request.getParameter("username");
		}
		PrintWriter out = response.getWriter();
		Connection conn = new DBConnection().connect();
		PreparedStatement stmt = null;
		String followedName;
		int followCount;
		String[] storyArray;
		String photoLink;
		if (conn == null) {
			out.println("Connection error");
		} else {
			try {
				stmt = conn.prepareStatement("SELECT followed_id FROM "
						+ TableNames.FOLLOW_TABLE + " WHERE follower_id=?");
				stmt.setInt(1, Utilities.getUserId(conn, f_username));
				ResultSet rs = stmt.executeQuery();
				request.setCharacterEncoding("utf8");
				response.setContentType("application/json");
				while (rs.next()) {
					int currentId = rs.getInt(1);
					followedName = Utilities.getUsername(conn, currentId);
					// Get how many people follow this user (with user ID = currentId).
					followCount = getFollowerCount(conn, currentId);
					// Get the name of the story fragments of this user (with user ID = currentId).
					storyArray = getStories(conn, currentId);
					// Get the profile picture link of this user (with user ID = currentId).
					photoLink = Utilities.getProfilePicture(conn, followedName);
					FollowObject followObject = new FollowObject(followedName,followCount, photoLink);
					followObject.setStoryTitles(storyArray);
					followedPeople.add(followObject);
				}

				if (f_requestType.equals("Android")) {
					JSONObject followedPeopleObject = new JSONObject();
					try {
						followedPeopleObject.put("followedPeople", followedPeople);
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					out.print(followedPeopleObject.toString());
				} else if (f_requestType.equals("Web")) {
					// After the operation is completed, redirect user to the Followers page.
					request.setAttribute("followedPeople", followedPeople);
					request.getRequestDispatcher("Following.jsp").forward(request, response);
				} else {
					// DO NOTHING!
				}
			} catch (SQLException e) {
				out.print(e.getMessage());
				e.printStackTrace();
			}
			try {
				conn.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	/**
	 * Finds the number of people who follow this user
	 * @param conn connection object to communicate with the database
	 * @param id ID of the user
	 * @return number of people that follows this user
	 * @throws SQLException
	 */
	private int getFollowerCount(Connection conn, int id) throws SQLException {
		ResultSet rs;
		PreparedStatement stmt = conn
				.prepareStatement("SELECT follower_id FROM "
						+ TableNames.FOLLOW_TABLE + " WHERE followed_id=?");
		stmt.setInt(1, id);
		rs = stmt.executeQuery();
		int count = 0;
		while (rs.next()) {
			count++;
		}
		return count;
	}

	/**
	 * Finds the names of the first 5 story fragments (at most) of the user 
	 * @param conn connection object to communicate with the database
	 * @param id ID of the user
	 * @return list of the names of at most 5 story fragments of the user
	 * @throws SQLException
	 */
	private String[] getStories(Connection conn, int id) throws SQLException {
		String[] result = new String[5];
		PreparedStatement stmt = conn.prepareStatement("SELECT title FROM "
				+ TableNames.STORIES_TABLE + " WHERE owner = ?");
		stmt.setInt(1, id);
		ResultSet rs2 = stmt.executeQuery();
		int counter = 0;
		while (rs2.next() && counter < 5) {
			String title = rs2.getString("title");
			result[counter] = title;
			++counter;
		}
		return result;
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		process(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		process(request, response);
	}

}
